const app = getApp()
import http from "../../utils/request.js";
const publicFun = require('../../utils/public');
const commonJS = require("../../utils/utils.js");

Page({
    /**
     * 页面的初始数据
     */
    data: {
        height: 0,
        dreamId: '', //梦境id
        coverImgUrl: '/media/bg/bg.webp', //封面默认图片
        dreamTitle: '',
        dreamContent: '',
        dreamAuth: 1, //权限，1：私密，2：公开
        tagName: '',
        dreamTagList: [], //梦境标签列表
        chooseTagList: [], //选择的标签
        authList: [{
            'value': 1,
            'name': '私密',
            'checked': true
        }, {
            'value': 2,
            'name': '公开',
            'checked': false
        }],
        tabList: [{
            id: 0,
            name: '公开'
        }, {
            id: 1,
            name: '私有'
        }],
        editorCtx: '',
        showTag: false,
        showColorPicker: false,
        colorBg: '#9e67f7',
        formats: {},
        keyboardHeight: 0,
        isIOS: false,
        enableFormats: ['bold', 'italic', 'underline']
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.dreamId) {
            this.setData({
                height: wx.getSystemInfoSync().windowHeight,
                dreamId: options.dreamId
            })
            this.getDreamDetail()
        } else {
            this.setData({
                height: wx.getSystemInfoSync().windowHeight
            })
        }

        //设备信息
        const platform = wx.getSystemInfoSync().platform
        const isIOS = platform === 'ios'
        this.setData({
            isIOS
        })
        const that = this
        this.updatePosition(0)
        let keyboardHeight = 0
        wx.onKeyboardHeightChange(res => {
            if (res.height === keyboardHeight) return
            const duration = res.height > 0 ? res.duration * 1000 : 0
            keyboardHeight = res.height
            setTimeout(() => {
                wx.pageScrollTo({
                    scrollTop: 0,
                    success() {
                        that.updatePosition(keyboardHeight)
                        that.editorCtx.scrollIntoView()
                    }
                })
            }, duration)
        })
    },

    updatePosition(keyboardHeight) {
        const toolbarHeight = 50
        const {
            windowHeight,
            platform
        } = wx.getSystemInfoSync()
        let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
        this.setData({
            editorHeight,
            keyboardHeight
        })
    },

    titleFocus(e) {
        this.setData({
            keyboardHeight: 0,
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.getDreamTag()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    //格式化
    format(e) {
        let {
            name,
            value
        } = e.target.dataset
        if (!name) return
        this.data.editorCtx.format(name, value)
    },
    changeEditor(e) {
        const {
            html,
            text,
            delta
        } = e.detail;
        console.log(html, text, delta)
        this.setData({
            dreamContent: html
        })
    },
    onStatusChange(e) {
        const formats = e.detail
        this.setData({
            formats
        })
    },
    editorFocus(e) {

    },

    onEditorReady() {
        wx.createSelectorQuery().in(this).select('#editor').context((res) => {
            this.data.editorCtx = res.context;
            this.data.editorCtx.setContents({
                html: this.data.dreamContent,
                success: function (res) {
                    console.log('富文本加载成功', res)
                }
            })
        }).exec()
    },

    radioAuthChange(e) {
        this.setData({
            dreamAuth: e.detail.value
        })
        let index = this.data.authList.findIndex(item => item.value == e.detail.value)
        if (index !== -1) {
            this.data.authList[index].checked = true
        }
    },

    //打开tag弹窗
    openTag() {
        this.setData({
            showTag: true
        })
    },

    tagChange(e) {
        this.setData({
            tagName: e.detail.value
        })
    },

    //增加标签
    addTag() {
        if (!this.data.tagName) {
            publicFun.Toast('名称不能为空')
            return false
        }
        let data = {
            userId: app.globalData.userId,
            name: this.data.tagName,
            bgColor: this.data.colorBg,
            color: commonJS.adjustColor(this.data.colorBg, -80)
        }
        http.Request({
            url: 'addTag',
            method: 'POST',
            data: data
        }).then(res => {
            if (res.code == 200) {
                publicFun.Toast('新增成功')
                this.setData({
                    tagName: ''
                })
                //查询列表
                this.getDreamTag()
            } else {
                publicFun.Toast('服务器错误')
            }
        });
    },

    //选择标签
    chooseTag(e) {
        let item = e.currentTarget.dataset.item
        let chooseTagList = this.data.chooseTagList
        let index = chooseTagList.findIndex(curr => curr.id == item.id)
        let index2 = this.data.dreamTagList.findIndex(curr => curr.id == item.id)
        if (index == -1) {
            chooseTagList.push(item)
        } else {
            chooseTagList.splice(index, 1)
        }
        if (this.data.dreamTagList[index2].selected) {
            this.data.dreamTagList[index2].selected = false
        } else {
            this.data.dreamTagList[index2].selected = true
        }
        this.setData({
            chooseTagList: chooseTagList,
            dreamTagList: this.data.dreamTagList
        })
    },

    //颜色选择器弹窗
    openColor() {
        this.setData({
            showColorPicker: true
        })
    },

    //颜色选择器改变
    onChangeColor(e) {
        this.setData({
            colorBg: e.detail.color
        })
    },

    //查询回显梦境
    getDreamDetail() {
        let data = {
            id: this.data.dreamId,
            userId: app.globalData.userId
        }
        http.Request({
            url: 'getDreamDetail',
            method: 'GET',
            data: data
        }).then(res => {
            if (res.code == 200 && res.data.result.length > 0) {
                let index = this.data.authList.findIndex(curr => curr.value == res.data.result[0].dreamAuth)
                if (index !== -1) {
                    this.data.authList[index].checked = true
                } else {
                    this.data.authList[index].checked = false
                }
                this.setData({
                    dreamId: res.data.result[0].id,
                    dreamTitle: res.data.result[0].title,
                    chooseTagList: res.data.result[0].tagList,
                    dreamContent: res.data.result[0].content,
                    coverImgUrl: res.data.result[0].cover,
                    dreamAuth: res.data.result[0].dreamAuth,
                    authList: this.data.authList,
                })
                this.createSelectorQuery().select('#editor').context((re) => {
                    if (!re) return
                    re.context.setContents({
                        html: res.data.result[0].content
                    })
                }).exec()
            } else {
                publicFun.Toast('服务器错误')
            }
        });
    },

    // 获取类型选择值
    getTypeValue(e) {
        this.setData({
            typeId: e.detail.id
        })
    },

    // 获取权限选择值
    getAuthValue(e) {
        this.setData({
            dreamAuth: e.detail.id
        })
    },

    // 获取题目
    getTitle(e) {
        this.setData({
            dreamTitle: e.detail.value
        })
    },

    // 提交数据
    submitDream() {
        if(!this.data.dreamTitle){
            publicFun.Toast('标题不能为空！')
            return false
        }
        let tagIds = []
        this.data.chooseTagList.forEach(item => {
            tagIds.push(item.id)
        })
        let data = {
            dreamId: this.data.dreamId,
            userId: app.globalData.userId,
            title: this.data.dreamTitle,
            tagIds: tagIds.toString(),
            content: this.data.dreamContent,
            cover: this.data.coverImgUrl,
            dreamAuth: this.data.dreamAuth
        }
        http.Request({
            url: 'addOrEditDream',
            method: 'POST',
            data: data,
        }).then(res => {
            if (res.code == 200) {
                publicFun.Toast(res.msg)
                wx.switchTab({
                    url: '/page/dreamList/dreamList',
                })
            } else {
                publicFun.Toast('服务器错误')
            }
        });
    },

    // 清空
    clearDream() {
        this.data.authList[0].checked = true
        this.data.authList[1].checked = false
        this.setData({
            dreamTitle: '',
            dreamDesc: '',
            dreamContent: '',
            dreamAuth: 1, //权限，1：仅自己可见，2：公开
            coverImgUrl: '', //封面默认图片
            chooseTagList: [], //选择的标签
            authList: this.data.authList,
            editorCtx: '',
            formats: {},
        })
        this.createSelectorQuery().select('#editor').context((res) => {
            if (!res) return
            res.context.setContents({
                html: ''
            })
        }).exec()
    },

    // 获取梦境标签
    getDreamTag() {
        http.Request({
            url: 'getTag',
            method: 'GET',
            data: {
                userId: app.globalData.userId
            }
        }).then(res => {
            if (res.code == 200) {
                res.data.forEach(item => {
                    let index = this.data.chooseTagList.findIndex(curr => curr.id == item.id)
                    if (index !== -1) {
                        item['selected'] = true
                    }
                })
                this.setData({
                    dreamTagList: res.data
                })
            } else {
                publicFun.Toast(res.msg)
            }
        });
    },


    // ------------------------------底部工具栏-----------------------------

    // 插入图片
    insertImage() {
        let that = this
        wx.chooseImage({ // 本地资源上传到服务器API
            success: function (res) {
                let suffix = res.tempFilePaths[0].substr(res.tempFilePaths[0].lastIndexOf('.') + 1)
                let params = {
                    type: '插入图片',
                    imgUrl: res.tempFilePaths[0],
                    userId: app.globalData.userId,
                    suffix: suffix
                }
                publicFun.uploadImg(params).then(res2 => {
                    that.data.editorCtx.insertImage({
                        src: res2.url,
                        width: '100%',
                        success: (res) => {
                            console.log(res)
                        }
                    })
                })
            }
        })
    },

    //选择封面图片
    chooseBgImg() {
        let that = this
        wx.chooseImage({ // 本地资源上传到服务器API
            success: function (res) {
                let suffix = res.tempFilePaths[0].substr(res.tempFilePaths[0].lastIndexOf('.') + 1)
                let params = {
                    type: '封面图片',
                    imgUrl: res.tempFilePaths[0],
                    userId: app.globalData.userId,
                    suffix: suffix
                }
                publicFun.uploadImg(params).then(res2 => {
                    that.setData({
                        coverImgUrl: res2.url
                    })
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})